<template>
  <div>
    <div class="list-table mb10">
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <el-select v-model="queryParams.fundAccountId" size="mini" style="width: 150px; padding-bottom: 10px" @change="getSubjectList">
          <el-option
            v-for="item in finFundAccountList"
            :key="item.id"
            :label="item.accountName"
            :value="item.id"
          />
        </el-select>
        {{ queryParams.yearMonth }}
      </el-form>
    </div>
    <template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="list-table">
            <div class="area-header header-flex">
              <span class="area-header-title">{{ $t('期末结账') }}</span>
              <div>
                <el-tag effect="plain" size="small" @click="carryoverHandle">{{ $t('结账') }}  </el-tag>
                <el-tag effect="plain" size="small" @click="reverseCarryoverHandle">{{ $t('反结账') }}</el-tag>
              </div>
            </div>
            <div class="qimojiezhuan">
              <div class="item">
                <div class="box-title">
                  <div class="title-name">结转损益</div>
                  <i class="el-icon-setting" @click="carryoverConfigHandle('month')" />
                </div>
                <div class="box-content">
                  <span class="money">金额:<span class="account1">{{ carryoverAmount }}</span></span>
                </div>
                <span class="btn-voucher" @click="generateVoucherHandle">生成凭证</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="list-table">
            <div class="area-header header-flex">
              <span class="area-header-title">{{ $t('年末结账') }}</span>
              <div>
                <el-tag effect="plain" size="small" @click="carryoverYearHandle">{{ $t('结账') }}  </el-tag>
                <el-tag effect="plain" size="small" @click="reverseCarryoverYearHandle">{{ $t('反结账') }}</el-tag>
              </div>
            </div>
            <div class="qimojiezhuan">
              <div class="item">
                <div class="box-title">
                  <div class="title-name">{{ '结转利润' }}</div>
                  <i class="el-icon-setting" @click="carryoverConfigHandle('year')" />
                </div>
                <div class="box-content">
                  <span class="money">{{ carryoverYear + '金额:' }}<span class="account1">{{ carryoverYearAmount }}</span></span>
                </div>
                <span class="btn-voucher" @click="generateVoucherYearHandle">生成凭证</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <el-dialog
      title="反结账"
      :visible.sync="backCarryOpen"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="backCarryLoading">
        <el-form ref="backCarryForm" :model="backCarryForm" :rules="backCarryRules" label-width="140px" label-position="left">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('周期')" prop="accountYearMonth">
                <el-select v-model="backCarryForm.accountYearMonth" value="" :placeholder="$t('周期')" filterable clearable>
                  <el-option
                    v-for="dict in backCarryoverRecordList"
                    :key="dict.accountYearMonth"
                    :label="$t(dict.accountYearMonth)"
                    :value="dict.accountYearMonth"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button size="small" @click="backCarryOpen = false">{{ $t('取消') }}</el-button>
          <el-button size="small" type="primary" @click="submitBackCarry">{{ $t('反结账') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="年末反结账"
      :visible.sync="backCarryYearOpen"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="backCarryYearLoading">
        <el-form ref="backCarryYearForm" :model="backCarryYearForm" :rules="backCarryYearRules" label-width="140px" label-position="left">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('周期')" prop="accountYear">
                <el-select v-model="backCarryYearForm.accountYear" value="" :placeholder="$t('周期')" filterable clearable>
                  <el-option
                    v-for="dict in backCarryoverRecordYearList"
                    :key="dict.accountYear"
                    :label="$t(dict.accountYear)"
                    :value="dict.accountYear"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button size="small" @click="backCarryYearOpen = false">{{ $t('取消') }}</el-button>
          <el-button size="small" type="primary" @click="submitBackCarryYear">{{ $t('反结账') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 添加或修改财务核心-结转记录对话框 -->
    <el-dialog :title="$t('结转损益参数设置')" :visible.sync="configOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <carryoverConfigForm ref="carryoverConfigForm" :config-type="configType" />
    </el-dialog>
  </div>
</template>

<script>
import { getFundAccountYearMonthList } from '@/api/fin/fundAccount/finFundAccount'
import {
  carryoverHandel,
  generateVoucher, generateVoucherYear,
  getCarryYearMonthList,
  startBackCarryover
} from '@/api/fin/carryoverRecord/finCarryoverRecord'
import carryoverConfigForm from '@/views/fin/carryoverRecord/carryoverConfigForm.vue'
import {
  checkYearRecord,
  getByFundAccountIdAndCarryoverRecordId, getYearRecordByFundAccountId
} from '@/api/fin/carryoverRecord/finCarryoverVoucherConfig'
import { mapActions, mapState } from 'vuex'
import {
  carryoverYearHandel,
  getCarryYearList,
  startBackCarryoverYear
} from '@/api/fin/carryoverRecord/finCarryoverRecordYear'

export default {
  components: {
    carryoverConfigForm
  },
  data() {
    return {
      options: [],
      // 弹出层标题
      title: '财务核心-结转记录',
      // 结转损益参数弹窗开关
      configOpen: false,
      backCarryOpen: false,
      backCarryLoading: false,
      backCarryYearLoading: false,
      backCarryYearOpen: false,
      carryoverAmount: 0,
      carryoverYearAmount: 0,
      carryoverYear: '',
      finFundAccountList: [],
      backCarryoverRecordList: [],
      backCarryoverRecordYearList: [],
      // 查询参数
      queryParams: {
        fundAccountId: undefined,
        yearMonth: undefined,
        carryoverRecordId: undefined,
        accountYearMonth: undefined,
        carryoverStatus: undefined
      },
      // 年度查询参数
      yearRecord: {
        fundAccountId: undefined,
        accountYear: undefined,
        carryoverRecordId: undefined,
        accountYearMonth: undefined,
        carryoverStatus: undefined
      },
      // 反结账表单
      backCarryForm: {
        accountYearMonth: undefined
      },
      // 年末反结账表单
      backCarryYearForm: {
        accountYear: undefined
      },
      // 表单校验
      backCarryRules: {
        accountYearMonth: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 表单校验
      backCarryYearRules: {
        accountYear: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      value: '',
      configType: 'month'
    }
  },
  computed: {
    ...mapState('finReport', ['finQueryParams'])
  },
  created() {
    this.getFundAccountList()
  },
  methods: {
    ...mapActions('finReport', ['changeQueryParams']),
    // 根据基金账套
    getSubjectList(fundAccountId) {
      if (fundAccountId === null || fundAccountId === undefined || fundAccountId === '') {
        return
      }
      if (this.finFundAccountList && this.finFundAccountList.length > 0) {
        this.finFundAccountList.forEach(item => {
          if (fundAccountId === item.id) {
            this.queryParams.carryoverRecordId = item.carryoverRecordId
            this.queryParams.yearMonth = item.yearMonth
          }
        })
      }
      this.getAmountInCarryoverConfig(this.queryParams.fundAccountId, this.queryParams.carryoverRecordId)
      const param = {
        fundAccountId: fundAccountId,
        yearMonth: this.queryParams.carryoverRecordId
      }
      console.log('param', param)
      this.changeQueryParams(param)
    },
    // 获取基金账套列表
    getFundAccountList() {
      this.finFundAccountList = []
      getFundAccountYearMonthList({}).then(response => {
        this.finFundAccountList = response.data
        if (this.finFundAccountList && this.finFundAccountList.length > 0) {
          const item = this.finFundAccountList[0]
          this.queryParams.fundAccountId = item.id
          this.queryParams.carryoverRecordId = item.carryoverRecordId
          this.queryParams.yearMonth = item.yearMonth
          if (this.finQueryParams.accountId && this.finQueryParams.yearMonth) {
            this.finFundAccountList.forEach(data => {
              if (data.id === this.finQueryParams.accountId) {
                this.queryParams.fundAccountId = data.id
                this.queryParams.carryoverRecordId = data.carryoverRecordId
                this.queryParams.yearMonth = data.yearMonth
              }
            })
          }
          this.getAmountInCarryoverConfig(this.queryParams.fundAccountId, this.queryParams.carryoverRecordId)
        }
      })
    },
    // 获取金额
    getAmountInCarryoverConfig(fundAccountId, carryoverRecordId) {
      getByFundAccountIdAndCarryoverRecordId(fundAccountId, carryoverRecordId).then(response => {
        if (response.data != null) {
          this.carryoverAmount = response.data.carryoverAmount
        } else {
          this.carryoverAmount = 0
        }
      })
      // 获取年度的金额，以及相关数据
      getYearRecordByFundAccountId(fundAccountId).then(response => {
        if (response.data != null) {
          this.yearRecord.carryoverRecordId = response.data.carryoverRecordId
          this.carryoverYearAmount = response.data.carryoverAmount
          this.carryoverYear = response.data.year ? response.data.year : ''
        } else {
          this.carryoverYearAmount = 0
        }
      })
    },
    /** 结账按钮操作 */
    carryoverHandle() {
      this.$confirm(this.$t('是否确认结转?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        const data = {
          id: this.queryParams.carryoverRecordId,
          accountYearMonth: this.queryParams.yearMonth,
          fundAccountId: this.queryParams.fundAccountId
        }
        return carryoverHandel(data)
      }).then(() => {
        this.getFundAccountList()
        this.msgSuccess(this.$t('结转成功'))
      }).catch(() => {
        this.loading = false
      })
    },
    /** 结账按钮操作 */
    carryoverYearHandle() {
      checkYearRecord(this.queryParams.fundAccountId, this.yearRecord.carryoverRecordId, this.queryParams.carryoverRecordId).then(response => {
        if (response.data.flag) {
          this.$confirm(this.$t('是否确认结转?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          }).then(() => {
            const data = {
              id: this.yearRecord.carryoverRecordId,
              carryoverRecordId: this.queryParams.carryoverRecordId,
              accountYearMonth: this.queryParams.yearMonth,
              fundAccountId: this.queryParams.fundAccountId
            }
            return carryoverYearHandel(data)
          }).then(() => {
            this.getFundAccountList()
            this.msgSuccess(this.$t('年末结转成功'))
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.msgError(this.$t(response.data.message))
        }
      })
    },
    submitBackCarry() {
      this.$refs['backCarryForm'].validate(valid => {
        if (valid) {
          // 获取当前账套已经结账的记录周期列表
          const data = {
            fundAccountId: this.queryParams.fundAccountId,
            accountYearMonth: this.backCarryForm.accountYearMonth
          }
          startBackCarryover(data).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('反结账成功'))
              this.getFundAccountList()
              this.backCarryOpen = false
            } else {
              this.msgError(response.msg)
            }
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 年末反结账操作
    submitBackCarryYear() {
      this.$refs['backCarryYearForm'].validate(valid => {
        if (valid) {
          // 获取当前账套已经结账的记录周期列表
          const data = {
            fundAccountId: this.queryParams.fundAccountId,
            accountYear: this.backCarryYearForm.accountYear
          }
          startBackCarryoverYear(data).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('年末反结账成功'))
              this.getFundAccountList()
              this.backCarryYearOpen = false
            } else {
              this.msgError(response.msg)
            }
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    /** 修改按钮操作 */
    reverseCarryoverHandle() {
      this.backCarryOpen = true
      this.backCarryLoading = true
      this.backCarryoverRecordList = []
      // 获取当前账套已经结账的记录周期列表
      const data = {
        fundAccountId: this.queryParams.fundAccountId,
        carryoverStatus: 'Y'
      }
      getCarryYearMonthList(data).then(response => {
        this.backCarryoverRecordList = response.data
        this.backCarryLoading = false
      })
    },
    /** 年末反结账按钮操作打开弹窗 */
    reverseCarryoverYearHandle() {
      this.backCarryYearOpen = true
      this.backCarryYearLoading = true
      this.backCarryoverRecordYearList = []
      // 获取当前账套已经结账的记录周期列表
      const data = {
        fundAccountId: this.queryParams.fundAccountId,
        carryoverStatus: 'Y'
      }
      getCarryYearList(data).then(response => {
        this.backCarryoverRecordYearList = response.data
        this.backCarryYearLoading = false
      })
    },
    /** 生成凭证按钮操作 */
    generateVoucherHandle() {
      getByFundAccountIdAndCarryoverRecordId(this.queryParams.fundAccountId, this.queryParams.carryoverRecordId).then(response => {
        if (response.data != null) {
          this.$confirm(this.$t('是否确认生成凭证?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          }).then(() => {
            const data = {
              id: this.queryParams.carryoverRecordId,
              accountYearMonth: this.queryParams.yearMonth,
              fundAccountId: this.queryParams.fundAccountId
            }
            return generateVoucher(data)
          }).then(() => {
            this.getFundAccountList()
            this.msgSuccess(this.$t('生成凭证成功'))
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.msgError(this.$t('请先配置结转损益参数设置'))
        }
      })
    },
    /** 生成凭证年末按钮操作 */
    generateVoucherYearHandle() {
      checkYearRecord(this.queryParams.fundAccountId, this.yearRecord.carryoverRecordId, this.queryParams.carryoverRecordId).then(response => {
        if (response.data.flag) {
          this.$confirm(this.$t('是否确认生成凭证?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          }).then(() => {
            const data = {
              id: this.yearRecord.carryoverRecordId,
              accountYearMonth: this.carryoverYear,
              fundAccountId: this.queryParams.fundAccountId
            }
            return generateVoucherYear(data)
          }).then(() => {
            this.getFundAccountList()
            this.msgSuccess(this.$t('生成凭证成功'))
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.msgError(this.$t(response.data.message))
        }
      })
    },
    /** 结转损益参数设置按钮操作 */
    carryoverConfigHandle(type) {
      this.configOpen = true
      this.configType = type
      this.$nextTick(() => {
        const data = {
          fundAccountId: this.queryParams.fundAccountId,
          carryoverRecordId: type === 'month' ? this.queryParams.carryoverRecordId : this.yearRecord.carryoverRecordId,
          accountYearMonth: type === 'month' ? this.queryParams.yearMonth : this.carryoverYear
        }
        this.$refs.carryoverConfigForm.init(data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.qimojiezhuan{
  display: flex;
  align-items: center;
  overflow: auto;
  padding-bottom: 10px;
  .item{
    margin: 20px;
    height: 200px;
    min-width: 250px;
    box-sizing: border-box;
    background: #fff;
    border-radius: 8px;
    position: relative;
    border: 1px solid #ddd;
    flex: 1;
    .box-title {
      height: 38px;
      line-height: 38px;
      background: #F7F7F7;
      position: relative;
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      border-bottom: 1px solid #ddd;
      i{
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
      }
    }
    .box-content{
      height: calc(100% - 45px);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .btn-voucher {
      position: absolute;
      bottom: -18px;
      left: calc(50% - 61px);
      letter-spacing: 2px;
      color: #93969B;
      font-size: 13px;
      padding: 10px 30px;
      white-space: nowrap;
      cursor: pointer;
      background: #fff;
      border: 1px solid #ddd;
      border-radius: 20px;
    }
  }
}
.header-flex{
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-tag{
    padding: 0 15px;
    cursor: pointer;
    border-radius: 2px;
    border-color: initial;
  }
}
.area-header-title{
  font-size: 16px;
  &::before{
    content: unset;
  }
}
</style>
